package com.metagurukul.metagranth.actionservlets;

import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.metagurukul.metagranth.service.QuestionService;
import com.metagurukul.metagranth.vo.Question;


/**
 * this function performs the function of update those questions which are being edited by the user
 * @author team MetaGranth
 *
 */
public class UpdateEditedQuestion extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
   
    public UpdateEditedQuestion() {
        super();

    }

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPerform(request, response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPerform(request, response);
	}
	/**
	 * this function will be called whenever a question is to be updated which are being edited by the user.
	 * gets the new titleName,questionDescription and tagList whichever among these are edited.
	 * Sets their corresponding values and calls the updateEditedQuestion function in the QuestionService Layer
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	
	private void doPerform(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true);
		if(session.getAttribute("userId")!=null){
		try {
		String editedTitle = request.getParameter("titlename");
		String editedQuestion = request.getParameter("description");
		String editedTagList = request.getParameter("tagnames");
		int questionID = Integer.parseInt(request.getParameter("questionID"));
		
		Question questionObj = new Question();
				
		questionObj.setQuesId(questionID);
		questionObj.setTitle(editedTitle);
		questionObj.setQuestion(editedQuestion);
		
		//calls the updateEditedQuestion function in the QuestionService Layer
		QuestionService.updateEditedQuestion(questionObj);
		
		editedTagList.trim();	
		//calls the updateEditedTags function to update the tags List corresponding to the tag table
		QuestionService.updateEditedTags(editedTagList, questionID);
		RequestDispatcher requestDispatcher = request.getRequestDispatcher("EditQuestionsServlet");
		requestDispatcher.forward(request, response);
		}
		catch (Exception exception) {
			request.setAttribute("errormsg", exception.getMessage());
			request.getRequestDispatcher("errorPage.jsp").forward(request,response);
		}
	}else{
		response.sendRedirect("index.jsp");
	}
		
	}

}
